import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import workflowApi from '../api/workflow';

// 模拟的工作流模板数据
const MOCK_TEMPLATES = [
    { id: 'template-1', name: '新用户欢迎流程' },
    { id: 'template-2', name: '内容审批流程' },
    { id: 'template-3', name: '客户支持工单流程' },
    { id: 'template-4', name: '空白模板' }
];

export function useWorkflow() {
    // 响应式状态
    const workflows = ref([]);
    const selectedWorkflow = ref(null);
    const activeWorkflows = ref(new Set());
    const workflowTemplates = ref(MOCK_TEMPLATES);
    const showCreateWorkflow = ref(false);
    const workflowFormRef = ref(null);
    const loading = ref(false);

    // 新建工作流的表单数据
    const newWorkflow = reactive({
        name: '',
        description: '',
        template: ''
    });

    // 表单验证规则
    const workflowRules = {
        name: [{ required: true, message: '请输入工作流名称', trigger: 'blur' }],
        description: [{ required: true, message: '请输入工作流描述', trigger: 'blur' }]
    };

    // 方法
    const fetchWorkflows = async () => {
        loading.value = true;
        try {
            const response = await workflowApi.getWorkflows();
            // 注意：API返回的数据结构可能需要适配
            // 假设返回的数据是 { success: true, data: [...] }
            if (response && response.data) {
                workflows.value = response.data;
                // 初始化时，默认选中第一个工作流
                if (workflows.value.length > 0) {
                    selectWorkflow(workflows.value[0]);
                }
                // 初始化活跃的工作流
                response.data.forEach(wf => {
                    if (wf.isActive) {
                        activeWorkflows.value.add(wf.id);
                    }
                });
            }
        } catch (error) {
            console.error("Failed to fetch workflows:", error);
            ElMessage.error('获取工作流列表失败');
        } finally {
            loading.value = false;
        }
    };

    const selectWorkflow = (workflow) => {
        selectedWorkflow.value = workflow;
        // 可以在这里根据需要加载工作流的详细信息
        // 例如：fetchWorkflowDetails(workflow.id);
    };

    const toggleWorkflow = async (workflow) => {
        const originalStatus = activeWorkflows.value.has(workflow.id);
        const newStatus = !originalStatus;

        try {
            await workflowApi.toggleWorkflow(workflow.id, newStatus);
            if (newStatus) {
                activeWorkflows.value.add(workflow.id);
            } else {
                activeWorkflows.value.delete(workflow.id);
            }
            ElMessage.success(`工作流已${newStatus ? '启用' : '禁用'}`);
        } catch (error) {
            console.error(`Failed to toggle workflow ${workflow.id}:`, error);
            ElMessage.error('切换工作流状态失败');
        }
    };
    
    const handleCreateWorkflow = async () => {
        if (!workflowFormRef.value) return;
        await workflowFormRef.value.validate(async (valid) => {
            if (valid) {
                loading.value = true;
                try {
                    const response = await workflowApi.createWorkflow(newWorkflow);
                    // 假设创建成功后返回新的工作流对象
                    if (response && response.data) {
                        workflows.value.push(response.data);
                        selectWorkflow(response.data); // 选中新创建的工作流
                        ElMessage.success('工作流创建成功');
                        showCreateWorkflow.value = false;
                        // 重置表单
                        newWorkflow.name = '';
                        newWorkflow.description = '';
                        newWorkflow.template = '';
                    }
                } catch (error) {
                    console.error("Failed to create workflow:", error);
                    ElMessage.error('工作流创建失败');
                } finally {
                    loading.value = false;
                }
            }
        });
    };

    const deleteSelectedWorkflow = () => {
        if (!selectedWorkflow.value) return;
        
        ElMessageBox.confirm(
            `确定要删除工作流 "${selectedWorkflow.value.name}" 吗？此操作不可恢复。`,
            '警告',
            {
                confirmButtonText: '确定删除',
                cancelButtonText: '取消',
                type: 'warning',
            }
        ).then(async () => {
            try {
                await workflowApi.deleteWorkflow(selectedWorkflow.value.id);
                const index = workflows.value.findIndex(wf => wf.id === selectedWorkflow.value.id);
                if (index !== -1) {
                    workflows.value.splice(index, 1);
                }
                selectedWorkflow.value = workflows.value.length > 0 ? workflows.value[0] : null;
                ElMessage.success('工作流已删除');
            } catch (error) {
                console.error("Failed to delete workflow:", error);
                ElMessage.error('删除工作流失败');
            }
        }).catch(() => {
            // 用户取消删除
        });
    };

    // onMounted(fetchWorkflows); // 在组件挂载时获取数据

    return {
        workflows,
        selectedWorkflow,
        activeWorkflows,
        workflowTemplates,
        showCreateWorkflow,
        workflowFormRef,
        newWorkflow,
        workflowRules,
        loading,
        fetchWorkflows,
        selectWorkflow,
        toggleWorkflow,
        handleCreateWorkflow,
        deleteSelectedWorkflow
    };
} 